package com.huas.service.serviceimpl;

import com.huas.constant.MessageConstant;
import com.huas.entity.LoginUser;
import com.huas.entity.User;
import com.huas.exception.AccountException;
import com.huas.mapper.LoginMapper;
import com.huas.mapper.MenuMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private LoginMapper loginMapper;
    @Resource
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库查询用户
        User user = loginMapper.findByAccount(username);

        if(Objects.isNull(user)){
            throw new AccountException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //数据库查询用户权限信息
        List<String> permissions = menuMapper.selectPermission(user.getId());
        //将权限信息封装进UserDetails对象LoginUser返回
        return new LoginUser(user,permissions);
    }
}
